import React, { Component } from 'react'
import { Tooltip, Button, Tree, Divider } from 'antd';
import { Form, Input, DatePicker, Select } from 'antd';
import { CheckCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'

import { buildStationNode } from 'src/util/utils';

import SparkChannel, { EE } from 'src/ipc/sparkchannel'

const LEVEL_OPTIONS = [
  {
    value: 1,
    label: '提示',
  },
  {
    value: 2,
    label: '警告',
  },
  {
    value: 3,
    label: '严重',
  },
];

/**
 * 
 * @param {*} et 
 * @param {*} sort sort为true表示一级分类
 * @returns 
 */
function buildEventTypeNode(et, sort = true) {
  const children = et.type_list && et.type_list.map(cet => buildEventTypeNode(cet, false));
  const node = {
    title: sort ? et.sort_desc : et.type_desc,
    key: sort ? `SORT-${et.sort}` : `TYPE-${et.type}`,
    children: children,
    data: et,
  };
  return node;
}

function getAllKeys(treeData) {
  const allKeys = [];
  function traverse(nodes) {
    for (const node of nodes) {
      allKeys.push(node.key);
      node.children && traverse(node.children);
    }
  }
  traverse(treeData);

  return allKeys;
}

class EventQueryPanel extends Component {
  constructor(props) {
    super(props);

    this.checkAllEventTypes = this.checkAllEventTypes.bind(this);
    this.onValuesChange = this.onValuesChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onFinish = this.onFinish.bind(this);

    this.formRef = React.createRef();

    this.state = {
      stationTreeData: [],
      eventTypeTreeData: [],
    }
  }

  async loadStation() {
    const channel = await SparkChannel();
    const resp = await channel.request_get_model_node_list();
    const stationList = resp.data.model_node_list;
    const treeData = stationList.map(s => buildStationNode(s, true));
    this.setState({ stationTreeData: treeData });
  }

  async loadEventType() {
    const channel = await SparkChannel();
    const resp = await channel.request_get_event_type_list();
    const sortList = resp.data.sort_list;
    const treeData = sortList.map(s => buildEventTypeNode(s));
    this.setState({ eventTypeTreeData: treeData });

    // const allKeys = getAllKeys(treeData);
    // this.formRef.current?.setFields([
    //   { name: 'type_list', value: allKeys }
    // ]);
  }

  componentDidMount() {
    this.loadEventType();
    this.loadStation();
  }

  checkAllEventTypes() {
    const allKeys = getAllKeys(this.state.eventTypeTreeData);
    this.formRef.current.setFields([
      { name: 'type_list', value: allKeys }
    ]);
  }


  onValuesChange(changedValues, allValues) {
    console.log('onValuesChange', changedValues, allValues);
  };

  async onSubmit() {
    try {
      const values = await this.formRef.current.validateFields();

      this.onFinish(values);
    } catch (err) {
      console.log('validateFields error', err);
    }
  }

  async onFinish(values) {
    const { date_range, fuzzy_search, type_list, device_list } = values;
    console.log('onFinish', values);

    const type_list_result = type_list.map(typeKey => {
      return typeKey.startsWith('TYPE-') ?
        typeKey.substr('TYPE-'.length) : null;
    }).filter(Boolean);
    const device_list2 = device_list || [];
    const device_list_result = device_list2.map(deviceKey => {
      return deviceKey.startsWith('DEVICE-') ?
        deviceKey.substr('DEVICE-'.length) : null;
    }).filter(Boolean);

    const query = {
      from: date_range[0],
      to: date_range[1],
      type_list: type_list_result,
      device_list: device_list_result,
      fuzzy_search,
    }
    console.log('list-hisevent', query);
    EE.emit('list-hisevent', query);
  }

  render() {
    const state = this.state;
    const formItemCss = { marginBottom: '8px' };
    const initialValues = {};

    const rangePresets = [
      {
        label: '今日',
        value: [dayjs().startOf('day'), dayjs().endOf('day')],
      },
      {
        label: '昨日',
        value: [dayjs().subtract(1, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')],
      },
      {
        label: '本月',
        value: [dayjs().startOf('month'), dayjs().endOf('month')],
      },
      {
        label: '上月',
        value: [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')],
      },
    ];
    return (
      <div className='query-panel'>

        <Form
          className='spd-form'
          colon={false}
          requiredMark={false}
          ref={this.formRef}
          initialValues={initialValues}
          onValuesChange={this.onValuesChange}>

          <Form.Item
            label="时间"
            name="date_range"
            style={formItemCss}
            rules={[
              {
                required: true,
              },
            ]}>
            <DatePicker.RangePicker
              presets={rangePresets}
              showTime={{
                defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('23:59:59', 'HH:mm:ss')]
              }}
              format="YYYY/MM/DD HH:mm:ss" />
          </Form.Item>

          <Form.Item
            label="搜索"
            name="fuzzy_search"
            style={formItemCss}>
            <Input placeholder="关键字搜索" />
          </Form.Item>

          <Form.Item
            label="级别"
            name="level"
            style={formItemCss}>
            <Select mode="multiple" options={LEVEL_OPTIONS} allowClear />
          </Form.Item>

          <Button block type="primary"
            style={formItemCss}
            onClick={this.onSubmit}>查询</Button>

          <Divider orientation="left" plain>报警类型
            <Tooltip title="全选">
              <Button type='link' size='small' icon={<CheckCircleOutlined />}
                onClick={this.checkAllEventTypes}></Button>
            </Tooltip>
          </Divider>
          <Form.Item
            name="type_list"
            style={formItemCss}
            rules={[
              {
                required: true,
                message: '请选择报警类型'
              },
            ]}
            valuePropName='checkedKeys'
            trigger='onCheck'>
            <Tree
              checkable
              height={110}
              virtual={false}
              treeData={state.eventTypeTreeData}
            />
          </Form.Item>

          <Divider orientation="left" plain>设备</Divider>
          <Form.Item
            name="device_list"
            className='form-item-tree'
            style={formItemCss}
            valuePropName='checkedKeys'
            trigger='onCheck'>
            <Tree
              checkable
              defaultExpandAll
              treeData={state.stationTreeData} />
          </Form.Item>

        </Form>
      </div>
    );
  }
}

export default EventQueryPanel